<template>
    <a-form layout='horizontal' ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item label="固件" name="id">
            {{ firmware.name }}
        </a-form-item>
        <a-form-item label="升级范围" name="range" :rules="[{required : true, message : '请选择升级范围'}]">
            <a-select v-model:value="formData.range" :options="rangeOptions"></a-select>
        </a-form-item>
        <a-form-item v-if="formData.range == 2" label="指定设备" name='devices' :rules="[{required : true, message : '请填写设备'}]">
            <a-textarea v-model:value="formData.devices" placeholder="一行一个设备号"></a-textarea>
        </a-form-item>
    </a-form>
</template>

<script lang="ts" setup>
    import { upgradeApi } from '@/api/Ota';
import { ref } from 'vue';
    const props = defineProps<{
        firmware:{name:string;id:number}
    }>()

    const formRef = ref()
    const rangeOptions = [{value : 1, label : '全部在线设备'}, {value : 2, label : '指定设备'}]

    const formData = ref({
        range : '',
        devices : '',
    })

    async function submit() {
        await formRef.value.validate()
        const params = {...formData.value}
        if(params.range == 1) {
            delete params.devices
        }else {
            params.devices = params.devices.split('\n').map(v => Number(v))
        }

        params.firmware = props.firmware.id

        const res = await upgradeApi(params)
    }

    defineExpose({
        submit
    })

</script>